package main

import (
	"fmt"
	"net/http"
)

type Context struct {
	Req      *http.Request
	Resp     http.ResponseWriter
	Index    int
	handlers []HandlerFun
}

func (c *Context) Next() {
	c.Index++
	if c.Index < len(c.handlers) {
		c.handlers[c.Index](c)
	}
}

func (c *Context) Abort() {
	c.Index = len(c.handlers)
}

type HandlerFun func(*Context)

type Engine struct {
	handlers []HandlerFun
}

func (e *Engine) Use(f HandlerFun) {
	e.handlers = append(e.handlers, f)
}

func (e *Engine) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	context := &Context{
		Req:      req,
		Resp:     resp,
		Index:    -1,
		handlers: e.handlers,
	}
	context.Next()
}

func AuthMiddleware(c *Context) {
	fmt.Println("认证中间件")
	c.Abort()
}

func LogMiddleware(c *Context) {
	fmt.Println("日志中间件")
	c.Next()
}

func main() {
	e := &Engine{}
	e.Use(LogMiddleware)
	e.Use(AuthMiddleware)
	fmt.Println("server start on 8080")
	http.ListenAndServe(":8080", e)
}
